package com.hzhr.iot.collect.protocol.processor;

import com.hzhr.iot.collect.Global;
import com.hzhr.iot.collect.constant.MessageFieldKeyEnum;
import com.hzhr.iot.collect.protocol.util.CachedCommandUtil;
import com.hzhr.iot.core.util.HzhrJsonUtil;
import com.hzhr.iot.core.util.HzhrStringUtils;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDeviceModel;
import com.hzhr.iot.device.sdk.model.iotDevice.IotDevicePutModel;
import com.hzhr.iot.device.sdk.service.Device_IotDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * NBIOT 冻结日期查询 处理器
 * @author 48310
 *
 */
@Component
public class MessageProcessor13 implements MessageProcessor {
	@Autowired
	CachedCommandUtil cachedCommandUtil;
	@Autowired
	Device_IotDeviceService device_iotDeviceService;
	@Autowired
	Global global;

	@Override
	public List<Map<MessageFieldKeyEnum, Object>> proccess(int protocolId, String deviceId, Map<MessageFieldKeyEnum, Object> parsedMessageObj) throws Exception {
		String freezingDay = HzhrStringUtils.obj2str(parsedMessageObj.get(MessageFieldKeyEnum.FREEZING_DAY));

		//查询物联网设备
		IotDeviceModel iotDeviceModel = null;
		String iotDeviceCode = HzhrTypeUtil.object2string(parsedMessageObj.get(MessageFieldKeyEnum.IOT_DEVICE_ID));
		if (!StringUtils.isEmpty(iotDeviceCode)) {
			Map<String, String> header = new HashMap<>();
			header.put("token", global.getFirstToken());
			Map<String, Object> query = new HashMap<>();
			query.put("_show", "one");
			query.put("_show_info", true);
			query.put("_equal_iotPlatformDeviceId", deviceId);
			iotDeviceModel = device_iotDeviceService.get(header, query).getModel();
		}
		if (iotDeviceModel == null) throw new Exception("物联网设备不存在");

		//更新上报时间
		Map<String, String> header = new HashMap<>();
		header.put("token", global.getFirstToken());
		Map<String, Object> query = new HashMap<>();
		IotDevicePutModel iotDevicePutModel = HzhrJsonUtil.convertObjectType(iotDeviceModel, IotDevicePutModel.class);
		iotDevicePutModel.setFreezingDay(freezingDay);
		device_iotDeviceService.putById(header, iotDeviceModel.getId(), query, iotDevicePutModel);

		//清除缓存指令
		cachedCommandUtil.deleteCachedCommand(deviceId,
				parsedMessageObj.get(MessageFieldKeyEnum.IOT_DEVICE_ID).toString(),
				parsedMessageObj.get(MessageFieldKeyEnum.MESSAGE_ID).toString());
		return null;
	}
}
